const axios =  require("axios")

const service = axios.create({
    // 超时
    timeout: 30 * 1000
})
function tansParams(params) {
    let result = ''
    for (const propName of Object.keys(params)) {
        const value = params[propName];
        var part = encodeURIComponent(propName) + "=";
        if (value !== null && value !== "" && typeof (value) !== "undefined") {
            if (typeof value === 'object') {
                for (const key of Object.keys(value)) {
                    if (value[key] !== null && value[key] !== "" && typeof (value[key]) !== 'undefined') {
                        let params = propName + '[' + key + ']';
                        var subPart = encodeURIComponent(params) + "=";
                        result += subPart + encodeURIComponent(value[key]) + "&";
                    }
                }
            } else {
                result += part + encodeURIComponent(value) + "&";
            }
        }
    }
    return result
}
service.interceptors.request.use(config => {
    if(config.method === 'post'){
        config.data = typeof config.data === 'object' ? JSON.stringify(config.data) : config.data
    }
    // get请求映射params参数
    if (config.method === 'get' && config.params) {
        let url = config.url + '?' + tansParams(config.params);
        url = url.slice(0, -1);
        config.params = {};
        config.url = url;
    }
    console.log(config.method,'\t',config.url,'\t',config.baseURL,'\t',config.timeout);
    return config
})
service.interceptors.response.use(
    res => {
        return res
    },
    error => {
        if(error.code === 'EAI_AGAIN'){
            error.msg='域名无法解析'
        }
        return {error:true,code:error.code, msg: error.msg||error.message}
    },
)
module.exports = service
